package org.hitchhike.web;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;

import org.hitchhike.common.web.controller.BaseController;
import org.hitchhike.core.domain.User;
import org.hitchhike.core.exception.BaseException;
import org.hitchhike.core.service.UserService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.alibaba.fastjson.JSON;

@Controller
@RequestMapping(value = "/")
public class LoginController extends BaseController<User, Long> {
  private Logger logger = LoggerFactory.getLogger(getClass());

  @Autowired
  private UserService userService;

  @RequestMapping(value = "loginForm", method = RequestMethod.GET)
  public String loginForm(Model model, HttpServletRequest request) {
    User user = (User) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
    request.getSession().setAttribute("user", user);
    request.getSession().setAttribute("contextPath", request.getContextPath());

    return redirectToUrl(viewName("front"));
  }

  @RequestMapping(value = "login", method = RequestMethod.GET)
  public String login(Model model) {
    return viewName("login");
  }

  @RequestMapping(value = "register", method = RequestMethod.GET)
  public String registerForm(Model model) {
    return viewName("register");
  }

  @RequestMapping(value = "register", method = RequestMethod.POST)
  public String register(@Valid User user, BindingResult result,
      RedirectAttributes redirectAttributes) {
    if (result.hasErrors()) {
      logger.error(JSON.toJSONString(result.getAllErrors()));
      return redirectToUrl(viewName("register"));
    }
    try {
      userService.save(user);
    } catch (Exception e) {
      throw new BaseException(e.getMessage());
    }
    redirectAttributes.addFlashAttribute("user", user);
    return redirectToUrl(viewName("login"));
  }

}
